<?php

class MySql
{

    protected $link;

    protected $statement;

    protected $record;

    protected $currentIndex;

    function getConnection(array $dbconfig)
    {
        if (empty($dbconfig['user']) || empty($dbconfig['pwd']) || empty($dbconfig['host']))
        {
            throw new Exception("dbconfig error!");
        }

        return mysql_connect($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd']);
    }

    /**
	 * @dsn mysql://localhost:3306/?user=root&pwd=ilsanbao
     */
    function __construct($dsn, $charset = 'utf-8')
    {
        $config = $this->parseDsn($dsn);
        $this->link = $this->getConnection($config);
        mysql_set_charset($charset, $this->link);
    }

    function parseDsn($dsn)
    {
        $url_parts = parse_url($dsn);

        var_dump($url_parts);

        $config = array();

        return $config;
    }

    function query($statement)
    {
        if (is_resource($this->record))
        {
            $this->free();
        }
        $this->record = mysql_query($statement, $this->link);

        return $this;
    }

    function indexer($field)
    {
        if (strlen($field) > 0)
        {
            $this->currentIndex = $field;
        }
    }

    function getRow()
    {
        if (is_resource($this->record))
        {
            return mysql_fetch_assoc($this->record);
        }
        return array();
    }

    function getCol()
    {

    }

    function getAll($indexer = '')
    {
        if (!is_resource($this->record))
        {
            return array();
        }

        $ret = array();
        while ($row = mysql_fetch_assoc($this->record))
        {
            if (isset($row[$this->currentIndex]))
            {
                $ret[$row[$this->currentIndex]] = $row;
            }
        }

        return $ret;
    }

    function getOne()
    {

    }



    function close()
    {
        if (is_resource($this->link))
        {
            mysql_close($this->link);
            $this->link = null;
        }
    }

    function free()
    {
        if (is_resource($this->record))
        {
            mysql_free_result($this->record);
            $this->record = null;
        }
    }

    function __destruct()
    {
        $this->free();
        $this->close();
    }
}